//
// NotifierMap.ts
// Author:qiuchun(362460803@qq.com)
// Time:2023.05.01 19:05:44
// Desc:管理类的父类，相关注册，注销等功能都在这里实现

import Notifier from "./Notifier";
import Observer from "./Observer";
import ObserverMap from "./ObserverMap";

export default class NotifierMap {
    private _map = new Map<string, Notifier>();

    constructor() {
    }

    //获取
    public retrieveItem(name: string): Notifier | undefined {
        let item = this._map.get(name);
        if (item == undefined) {
            if (this.hasItemCaseInsensitive(name) == true) {
                throw new Error("name = " + name + " is CaseInsensitive");
            }
            else {
                throw new Error("name = " + name + ",item is not exist");
            }
        }

        return item;
    }
    //注册
    public registerItem(notifier: Notifier): void {
        let name = notifier.getName();
        if (this._map.has(name) == true) {
            return;
        }

        //注册通知者
        this._map.set(name, notifier);

        //注册观察者
        let interests = notifier.listNotificationInterests();
        if (interests) {
            let len = interests.length;
            if (len > 0) {
                let observer = new Observer(notifier.handleNotification, notifier);
                for (var i = 0; i < len; i++) {
                    ObserverMap.getInstance().registerObserver(interests[i], observer);
                }
            }
        }
        notifier.onRegister();
    }
    //判断是否存在
    public hasItem(name: string): boolean {
        let result = this._map.has(name);
        if (result == false) {
            this.hasItemCaseInsensitive(name);
        }
        return result;
    }

    //移除
    public removeItem(name: string) {

        let notifier = this._map.get(name);
        if (!notifier) {
            return null;
        }
        let interests = notifier.listNotificationInterests();
        if (interests) {
            let i = interests.length;
            while (i--) {
                ObserverMap.getInstance().removeObserver(interests[i], notifier);
            }
        }
        this._map.delete(name);
        notifier.onRemove();
        return notifier;
    };

    //不区分大小写来判断存在
    public hasItemCaseInsensitive(name: string): boolean {
        if (name == null || typeof name != "string") {
            return false;
        }

        //遍历
        this._map.forEach((value: Notifier, key: string) => {
            //不相等，忽略大小写却相当，说明有人把key的大小写弄错了。
            if (key !== name && key.toLowerCase() === name.toLowerCase()) {
                console.log("Mvp Worn:注意大小写。 key = " + key + ",name = " + name + ".")
                return true;
            }
        });
        return false;
    }


}